package com.dat255.tentatime;

import java.text.ParseException;

import com.dat255.tentatime.es.ExternalStorage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * This class will submit an exam to the server
 * The user is able to enter exam details
 * and add the exam to the server
 * @author Joseph
 *
 */
public class AddExamActivity extends Activity{

	private EditText courseid, coursename, courseplace;
	private DatePicker datepicker;
	private TimePicker timepicker;
	private Button buttonSave, buttonCancel;
	//Dialog ID
	private static final int DIALOG_ID = 47;
	
	private boolean sucess = false;

	private String date,time;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//Set
		setContentView(R.layout.exam_form);
		
		this.attachGUIcomponents();
		
        //set listeners
        buttonSave.setOnClickListener(saveListener);
        buttonCancel.setOnClickListener(cancelListener);
        
       
        
        
	}
	
	 /**
     * The internal method will "connect" the input/output components
     * of the GUI for this activity for use in this code
     */
    private void attachGUIcomponents(){
    	
    	 //Assign components
        courseid = (EditText) findViewById(R.id.formCourseID);
        coursename = (EditText) findViewById(R.id.formCourseName);
        courseplace = (EditText) findViewById(R.id.formPlace);
        
        datepicker = (DatePicker) findViewById(R.id.datePicker);
        timepicker = (TimePicker) findViewById(R.id.timePicker);
        
        buttonSave = (Button) findViewById(R.id.buttonSave);
        buttonCancel = (Button) findViewById(R.id.buttonCancel);
    	
    	
    	
    }
    /**
     * This internal method will validate the input entred on the form
     * and assist the user to correct the mistakes
     * @return true if every input parameter on the form is correct
     */
    private boolean validateInput(){
    	
    		boolean procced = true;
    	   
		   if(!InputUtility.validateCourseID(courseid.getText().toString().trim())){
			   
			   
			   
			   Toast.makeText(AddExamActivity.this," Not a valid courseid! Please review the entred data!", Toast.LENGTH_LONG).show();
			   procced = false;
			   
		   }else if (!InputUtility.validateName(coursename.getText().toString().trim())){
				
			   Toast.makeText(AddExamActivity.this," Not a valid coursename!", Toast.LENGTH_LONG).show();
			   procced = false;

			}else if(!InputUtility.validatePlace(courseplace.getText().toString().trim())){
				
				Toast.makeText(AddExamActivity.this," Not a valid name for place! Please review the entred data!", Toast.LENGTH_LONG).show();
 			   procced = false;
				
				
			}else if(!InputUtility.validateTime(time)){
				
				Toast.makeText(AddExamActivity.this," Not a valid time! Please review the entred data!", Toast.LENGTH_LONG).show();
 			   procced = false;
				
			} else
				try {
					if(!InputUtility.validateDate(date)){
						
						Toast.makeText(AddExamActivity.this," Old dates and todays are not valid! Please review the entred data!", Toast.LENGTH_LONG).show();
	        			   procced = false;
						
					}else{
						
						procced = true;
						
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    	
    	
		   		return procced;
    	
    }


	//Create an anonymous implementation of OnClickListener
    private OnClickListener saveListener = new OnClickListener() {
        public void onClick(View v) {
        
        	AlertDialog.Builder builder = new AlertDialog.Builder(AddExamActivity.this);
        	
			builder.setMessage("Do you want to save the exam?")
			       .setCancelable(false)
			       .setTitle("Confirmation")
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	  
			        	 time = timepicker.getCurrentHour().toString() + ":" + timepicker.getCurrentMinute();
			           	// jan starts at 0
			           	date = datepicker.getDayOfMonth() + "/" + (datepicker.getMonth()+1) + "/" + datepicker.getYear();
			        	   if(InputUtility.connectedToTheInternet(AddExamActivity.this)){
			        		  
			        		
								
			        	   
			        	   if(validateInput()){
			        		   showDialog(DIALOG_ID);
			        		new SubmitExam().execute();
			        	   }
			           
			        	   }else{
			        		   
			        		   Toast.makeText(AddExamActivity.this, "No Internet Connection!", Toast.LENGTH_LONG).show();
			        	   }
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			
			AlertDialog alert = builder.create();
					alert.show();
        } 
        		
     
    };
     
    // Create an anonymous implementation of OnClickListener
    private OnClickListener cancelListener = new OnClickListener() {
        public void onClick(View v) {
        	
        	AlertDialog.Builder builder = new AlertDialog.Builder(AddExamActivity.this);
        	
			builder.setMessage("Do you want to cancel")
			       .setCancelable(false)
			       .setTitle("Confirmation")
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	  
			        	   Intent intent = new Intent(); 
			                intent.setClass(getApplicationContext(), FindActivity.class);
			                startActivity(intent);
			                finish();
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			                dialog.cancel();
			           }
			       });
			
			AlertDialog alert = builder.create();
					alert.show();
        } 
    };
    
	
    /**
	 * Creates a progressdialog, that is displayed  when the user makes a search	
	 */
	  @Override
	  protected Dialog onCreateDialog(int id) {
	   
		  switch (id) {
	    case DIALOG_ID: {
	    	
	      ProgressDialog dialog = new ProgressDialog(this);
	      
	      dialog.setMessage(AddExamActivity.this.getString(R.string.dialogmsg));
	      
	      dialog.setIndeterminate(true);
	      
	      dialog.setCancelable(true);
	      
	      return dialog;
	    }
	    
		  }

	    return null;
	  }
	
	  
	  @Override
		protected void onResume() {
		  UserState app = ((UserState)AddExamActivity.this.getApplication());
			super.onResume();
			
			if(!app.getState()){
				Toast.makeText(this, "Form removed due to inactivity", Toast.LENGTH_LONG).show();
				
				finish();
				
			}
			
		}
	
    /*****************************************************/
	/************** ASYNCTASKS      **********************/
	/*****************************************************/
			
		
	



	/**
	 * This internal class, will help us create an asynctask when we search for an exam
	 * in the server database, instead of burden the UI thread	
	 * @author Joseph
	 *
	 */
	private class SubmitExam extends AsyncTask<Void,Integer,String>{

		
		/**
		 * This method will try to submit an exam to the sercer
		 */
		@Override
		protected String doInBackground(Void... arg0) {
			String msg =""; 
			String time = timepicker.getCurrentHour().toString() + ":" + timepicker.getCurrentMinute();
        	// jan starts at 0
        	String date = datepicker.getDayOfMonth() + "/" + (datepicker.getMonth()+1) + "/" + datepicker.getYear();
			
        	
			try {
				
				//if the courseid don't exist, exception will vill be thrown
				ExternalStorage.findById(courseid.getText().toString());
				
				msg = "The exam already exist on the server";
				
				
			
			} catch (Exception e) {
				try {
					ExternalStorage.add(coursename.getText().toString().trim(),
							courseid.getText().toString().trim(), date, time, 
							courseplace.getText().toString().trim());
					msg = "The exam was succesfully stored on the server";
					sucess = true;
				} catch (Exception e1) {
					
					msg = "Some error on the server!";
				}
					
					
			}
			
			return msg;
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		/**
		 * This method is executed after doInBackground and will present the result 
		 * from doInBackground
		 */
		@Override
		protected void onPostExecute(String result) {
			
			super.onPostExecute(result);
			//Disable dialog box
			dismissDialog(DIALOG_ID);
			
			Toast.makeText(AddExamActivity.this, result, Toast.LENGTH_LONG).show();
			
			//If submit was successful move to next activity
			if(sucess){
				
				
				Intent intent = new Intent(AddExamActivity.this, FindActivity.class);
				AddExamActivity.this.startActivity(intent); 
				finish();
						
	    };
	    
			
			
		}
		

	}
	

	}


